<template>
  <div>
    <!-- 城市列表出口 -->
    <router-view />
    <van-nav-bar class="nav-bar" title="城市列表" left-arrow @click-left="$router.push('/shouye')" />
    <van-index-bar :index-list="indexList" highlight-color="#1cb676">
    <!-- 热门城市 -->
      <van-index-anchor index="#">当前城市</van-index-anchor>
      <van-cell :title="title" />
      <van-index-anchor index="热">热门城市</van-index-anchor>
      <van-cell v-for="(hotcity, index) in hotcity" :key="index" @click="shouy(hotcity.label)" >{{
        hotcity.label
      }}</van-cell>

    <!-- 城市列表 -->
    <template v-for="(item, index) in arr">
      <!-- 判断首字母相同的地区所在的新数组长度是否大于0，大于零就用这个首字母作为，标记，如果有就用 -->
      <van-index-anchor
      :key="list[index]"
      :index="
      item.length > 0 ? item[0].short[0].toUpperCase() : list[index]
      "
      >
      {{ item.length > 0 ? item[0].short[0].toUpperCase() : list[index] }}
      </van-index-anchor>
      <!-- 如果首字母相同的城市的数组，存在就渲染到页面 -->
      <template v-if="item.length">
        <van-cell
        v-for="elment in item"
        :key="elment.value"
        :title="elment.label"
        @click="shouy(elment.label)"
        />
      </template>
      <template v-if="!item.length">
      <van-cell :key="index" title="暂无城市" />
      </template>
    </template>
    </van-index-bar>
  </div>
</template>

<script>
import { getCityList, Getcityhot } from '@/api/other'
export default {
  data () {
    return {
      cityname: '',
      title: '杭州',
      indexList: ['#', '热', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ],
      list: ['#', '热', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
      ],
      level: 1,
      hotcity: [],
      arr: [] // 用来存放帅选出来首字母相同的数据
    }
  },
  async created () {
    // 热门城市
    const res = await Getcityhot()
    // console.log(res)
    this.hotcity = res.body
    // 城市列表
    const { body } = await getCityList(this.level)
    // console.log(body)
    // this.citydate = body
    // 把城市首字母相同的筛选出来到arr里
    for (let i = 0; i < this.list.length; i++) {
      this.arr.push(body.filter(item => item.short[0].toUpperCase() === this.list[i]))
    }
  },
  methods: {
    shouy (value) {
      console.log(value)
      localStorage.setItem('cityname', value)
      this.$router.push('/shouye')
      this.title = value
      console.log(this.title)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
